import { Injectable } from '@nestjs/common';
import { InjectDataSource, InjectRepository } from '@nestjs/typeorm';
import { ArticleContentLikeEntity } from './article-content-like.entity';
import { DataSource, Repository } from 'typeorm';
import { isNil } from 'lodash';
import { UserEntity } from '~/modules/user/user.entity';
import { UserWechatEntity } from '~/modules/user/user-wechat/user-wechat.entity';
import { ArticleContentEntity } from '../article-content.entity';

@Injectable()
export class ArticleContentLikeService {
  constructor(
    @InjectRepository(ArticleContentLikeEntity)
    private readonly articleContentLikeRepo: Repository<ArticleContentLikeEntity>,
    @InjectDataSource()
    private readonly datasource: DataSource
  ) {}

  async create(contentId: number, userId: number): Promise<ArticleContentLikeEntity> {
    return await this.articleContentLikeRepo.save({
      user: { id: userId },
      content: { id: contentId },
    });
  }

  async delete(contentId: number, userId: number): Promise<void> {
    await this.articleContentLikeRepo.delete({ user: { id: userId }, content: { id: contentId } });
  }

  async hasLiked(contentId: number, userId: number): Promise<boolean> {
    const liked: ArticleContentLikeEntity = await this.articleContentLikeRepo.findOneBy({
      user: { id: userId },
      content: { id: contentId },
    });

    return !isNil(liked);
  }

  /**
   * 获取用户的点赞数量
   * @param userId 用户ID
   * @returns 用户的点赞数量
   */
  async getUserLikeCount(userId: number): Promise<number> {
    return await this.articleContentLikeRepo.count({
      where: { user: { id: userId } },
    });
  }

	/**
	 * 统计数据
	 * @returns
	 */
  async getAllCount(): Promise<Partial<ArticleContentLikeEntity>[]> {
    return await this.datasource
      .createQueryBuilder()
      .addSelect('article_like.created_at', 'createdAt')
      .addSelect('userWechat.nickname', 'nickname')
      .addSelect('userWechat.phone', 'phone')
      .addSelect('articleContent.code', 'articleCode')
      .addSelect('articleContent.name', 'articleName')
      .from(ArticleContentLikeEntity, 'article_like')
      .leftJoin(UserEntity, 'user', 'user.id = article_like.user_id')
      .leftJoin(UserWechatEntity, 'userWechat', 'userWechat.id = user.wechat_id')
      .leftJoin(
        ArticleContentEntity,
        'articleContent',
        'articleContent.id = article_like.content_id'
      )
      .orderBy('article_like.id', 'DESC')
      .getRawMany();
  }
}
